package main

import (
	"fmt"
	"net"
	"net/http"
	"io/ioutil"
)

func sayHello(w http.ResponseWriter, r *http.Request){
    b, _ := ioutil.ReadFile("./hello.html")
	_, _ = fmt.Fprintln(w, string(b))
}

func sayWorld(w http.ResponseWriter, r *http.Request){
    _, _ = fmt.Fprintln(w, "<h1>World Golang!</h1>")
}

var localIP string

const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
)

// 获取本机网卡IP

func GetLocalIP() (ip string, err error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return
	}
	for _, addr := range addrs {
		ipAddr, ok := addr.(*net.IPNet)
		if !ok {
			continue
		}
		if ipAddr.IP.IsLoopback() {
			continue
		}
		if !ipAddr.IP.IsGlobalUnicast() {
			continue
		}
		return ipAddr.IP.String(), nil
	}
	return
}

// RemoteIp 返回远程客户端的 IP
func RemoteIp(wrt http.ResponseWriter, req *http.Request) {
	remoteAddr := req.RemoteAddr
	if ip := req.Header.Get(XRealIP); ip != "" {
		remoteAddr = ip
	} else if ip = req.Header.Get(XForwardedFor); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}
	localIP, _ := GetLocalIP()
	//return remoteAddr
	_, _ = fmt.Fprintln(wrt, "<h1>Server_IP: "+localIP+"</h1>\n<h1>Client_IP: "+remoteAddr+"</h1>")
}


func main() {
	http.HandleFunc("/hello",sayHello)	
	http.HandleFunc("/world",sayWorld)	
	http.HandleFunc("/info", RemoteIp)
	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		fmt.Printf("http serve failed, err:%v\n", err)
		return
	}
}
